﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyShop
{
    public partial class Basket : System.Web.UI.Page
    {
        public class OrderedProductsObj
        {
            public string ID { get; set; }
            public string OrderId { get; set; }
            public string Count { get; set; }
        }
        public List<OrderedProductsObj> DataOrderedProducts { get; set; }

        public class OrderedUsersObj
        {
            public string ID { get; set; }
            public string FirstName { get; set; }
            public string LastNameName { get; set; }
            public string Email { get; set; }
            public string Phone { get; set; }
            public string Delivery { get; set; }
            public DateTime Date { get; set; }
            public int Status { get; set; }
        }
        public List<OrderedUsersObj> DataOrderedUser { get; set; }

        public class BasketProductObj
        {
            public string ID { get; set; }
            public string GroupID { get; set; }
            public string CompanyID { get; set; }
            public string ModelName { get; set; }
            public string Description { get; set; }
            public string Price { get; set; }
            public string CountAvailable { get; set; }
            public bool Approval { get; set; }            
            public string CountOrdered { get; set; }
        }
        public List<BasketProductObj> DataProduct { get; set; }

        public int CurrentOrderId;


        protected void Page_Loaded(object sender, EventArgs e)
        {
            CalculationAmount();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
           
            List<string> listProd = new List<string>();
            listProd = (List<string>)Session["ProductsInBasket"];
            if (listProd == null) return;
            DataSet dataSet = new DataSet();
            string tempQuery = "";
            foreach (string s in listProd)
            {
                tempQuery += " ID = " + s + " or";
            }
            tempQuery = tempQuery.Remove(tempQuery.Length - 2, 2);

            using (SqlConnection sqlcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ShopConnectionString"].ConnectionString))
            {
                SqlCommand com = new SqlCommand("select * from Product WHERE" + tempQuery, sqlcon);
                DataTable dataTable = new DataTable();
                SqlDataAdapter dataAdapter = new SqlDataAdapter();
                dataAdapter.SelectCommand = com;
                dataAdapter.Fill(dataTable);
                dataSet.Tables.Add(dataTable);
                GetDataProduct(dataTable);
            }
            if (User.Identity.Name != "")
            {
                using (SqlConnection sqlcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ShopConnectionString"].ConnectionString))
                {
                    SqlCommand com = new SqlCommand("select * from Users WHERE UserName = '" + User.Identity.Name + "'", sqlcon);
                    DataTable dataTable = new DataTable();
                    DataSet dataSetUser = new DataSet();
                    SqlDataAdapter dataAdapter = new SqlDataAdapter();
                    dataAdapter.SelectCommand = com;
                    dataAdapter.Fill(dataTable);
                    dataSetUser.Tables.Add(dataTable);
                    GetDataUser(dataTable);
                }
            }
            
            CalculationAmount();
                    
        }

        public void GetDataUser(DataTable prod)
        {
            //DataRow row = prod.Rows[0];

            //FirstName = row["UserName"].ToString();

            //List<BasketProductObj> mainResult = new List<BasketProductObj>();
            foreach (DataRow item in prod.Rows)
            {
                FirstName.Text = item["FirstName"].ToString();
                LastName.Text = item["LastName"].ToString();
                Email.Text = item["Email"].ToString();

                //mainResult.Add(new BasketProductObj
                //{
                //    ID = item["ID"].ToString(),
                //    GroupID = item["GroupID"].ToString(),
                //    CompanyID = item["CompanyID"].ToString(),
                //    ModelName = item["ModelName"].ToString(),
                //    Description = item["Description"].ToString(),
                //    Price = item["Price"].ToString(),
                //    CountOrdered = "1",
                //    Approval = true,
                //    CountAvailable = item["Count"].ToString()
                //});
            }
            //DataProduct = mainResult;
            //if (!IsPostBack)
            //{
            //    BindProduct();

            //}
        }

        public void GetDataProduct(DataTable prod)
        {
            List<BasketProductObj> mainResult = new List<BasketProductObj>();
            foreach (DataRow item in prod.Rows)
                {
                    mainResult.Add(new BasketProductObj
                    {
                        ID = item["ID"].ToString(),
                        GroupID = item["GroupID"].ToString(),
                        CompanyID = item["CompanyID"].ToString(),
                        ModelName = item["ModelName"].ToString(),
                        Description = item["Description"].ToString(),
                        Price = item["Price"].ToString(),
                        CountOrdered = "1",
                        Approval = true,
                        CountAvailable = item["Count"].ToString()
                    });                    
            }
            DataProduct = mainResult;
            if (!IsPostBack)
            {
                BindProduct();

            }
        }

        public void BindProduct()
        {
            GridViewProduct.DataSource = DataProduct;
            GridViewProduct.DataBind();           
        }

        protected void OrderButton_Click(object sender, EventArgs e)
        {            
            if (this.IsValid && IsNoolOrder()) 
            {
                using (SqlConnection sqlcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ShopConnectionString"].ConnectionString))
                {
                    SqlCommand cmd = new SqlCommand("InsertOrderedUsers", sqlcon);
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add(new SqlParameter("@StatusOrder", SqlDbType.Int));
                    cmd.Parameters["@StatusOrder"].Value = 1;
                    cmd.Parameters.Add(new SqlParameter("@Delivery", SqlDbType.NVarChar, 50));
                    cmd.Parameters["@Delivery"].Value = DeliveryDropDownList.SelectedValue;
                    cmd.Parameters.Add(new SqlParameter("@Phone", SqlDbType.Int));
                    cmd.Parameters["@Phone"].Value = PhoneNumber.Text;
                    cmd.Parameters.Add(new SqlParameter("@Email", SqlDbType.NVarChar, 50));
                    cmd.Parameters["@Email"].Value = Email.Text; 
                    cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 50));
                    cmd.Parameters["@FirstName"].Value = FirstName.Text;
                    cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 50));
                    cmd.Parameters["@LastName"].Value = LastName.Text;
                    cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4));
                    cmd.Parameters["@Id"].Direction = ParameterDirection.Output;
                    sqlcon.Open();
                    try {
                        
                        cmd.ExecuteNonQuery();
                        CurrentOrderId = Convert.ToInt32(cmd.Parameters["@Id"].Value);
                    }                    
                    finally
                    {
                        sqlcon.Close();
                    }
                    AddOrder(CurrentOrderId);
                }
                Session["ProductsInBasket"] = null;
                Response.Redirect("Default.aspx?");
            }
            
        }

        
        protected void AddOrder(int orderId) 
        { 
            foreach (GridViewRow di in GridViewProduct.Rows)
            {
                int tempApprovalProduct = 0;
                CheckBox chkBx = (CheckBox)di.FindControl("Approval_checkbox");
                if (chkBx != null && chkBx.Checked)
                {
                    TextBox txt = (TextBox)di.FindControl("Count_textbox");
                    tempApprovalProduct = di.RowIndex;
                    using (SqlConnection sqlcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ShopConnectionString"].ConnectionString))
                    {
                        SqlCommand cmd = new SqlCommand("InsertOrderedProduct", sqlcon);
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.Add(new SqlParameter("@OrderId", SqlDbType.Int));
                        cmd.Parameters["@OrderId"].Value = orderId;
                        cmd.Parameters.Add(new SqlParameter("@ProductId", SqlDbType.Int));
                        cmd.Parameters["@ProductId"].Value = DataProduct[tempApprovalProduct].ID;
                        cmd.Parameters.Add(new SqlParameter("@Count", SqlDbType.Int));
                        cmd.Parameters["@Count"].Value = txt.Text;
                        sqlcon.Open();
                        try {
                            int tempId = cmd.ExecuteNonQuery();
                        }                    
                        finally
                        {
                            sqlcon.Close();
                        }
                    }
                }
            }
        }

        public bool IsNoolOrder()
        {
            bool result = false;
            foreach (GridViewRow di in GridViewProduct.Rows)
            {
                CheckBox chkBx = (CheckBox)di.FindControl("Approval_checkbox");
                if (chkBx != null && chkBx.Checked) return result = true;                
            }
            return result;
        }

        protected void ButtonGoBack_Click(object sender, EventArgs e)
        {
           
                Response.Redirect("Default.aspx?");

        }

        protected void AmounButton_OnClick(object sender, EventArgs e)
        {
            CalculationAmount();
        }

        protected void CalculationAmount()
        {
            if (GridViewProduct != null)
            {
                int tempApprovalProduct = 0;
                var totalAmount = 0;
                foreach (GridViewRow row in GridViewProduct.Rows)
                {
                    CheckBox box = (CheckBox)row.FindControl("Approval_checkbox");

                    if (box != null && box.Checked)
                    {
                        TextBox txt = (TextBox)row.FindControl("Count_textbox");
                        tempApprovalProduct = row.RowIndex;
                        var tempPrice = DataProduct[tempApprovalProduct].Price;

                        totalAmount += Convert.ToInt32(txt.Text) * Convert.ToInt32(tempPrice); 
                        
                    }
                }

                TotalAmount.Text = totalAmount + "$";
            }
           
        }
    }
}